package common

import (
	"go-scripts/config"
	"gopkg.in/mgo.v2"
)

var mongodb *DB = nil

func getMongo(db string) (*mgo.Database,*mgo.Session,error) {
	//获取配置文件
	conf := config.GetConfig()
	if conf == nil {
		return nil,nil,NewError("Config is not init", MongoError)
	}
	mongoConfig := conf.GetMongoConfig()
	if db == "" {
		error := NewError("库名不能为空", MongoError)
		return nil,nil,error
	}
	dbConfig :=mongoConfig[db]
	session,err := mgo.Dial(dbConfig.(map[string]interface{})["Url"].(string))
	if err != nil {
		return nil,nil,err
	}
	return session.DB(dbConfig.(map[string]interface{})["DB"].(string)),session,nil
}

type DB struct {
	mongo* mgo.Database
	abnormal* mgo.Database
	session* mgo.Session
}

func GetMongo() *DB {
	logger := GetLogger()
	logger.Info("初始化mongo")
	if mongodb != nil {
		return mongodb
	}
	mongodb = new(DB)
	var err error
	mongodb.mongo,mongodb.session,err = getMongo("mongo")
	if err != nil {
		logger.Error("初始化mongo失败")
		logger.Fatal(err.Error())
	}
	mongodb.abnormal,mongodb.session,err = getMongo("abnormal")
	if err != nil {
		logger.Error("初始化mongo失败")
		logger.Fatal(err.Error())
	}
	return mongodb
}

func (model* DB) GetMongoCollection(modelName string) *mgo.Collection {
	return model.mongo.C(modelName)
}

func (model* DB) GetAbnormalCollection(modelName string) *mgo.Collection {
	return model.abnormal.C(modelName)
}

func (model* DB) Close() {
	model.session.Close()
}